import com.sina.microblog.MicroBlog;
import com.sina.microblog.data.MicroBlogUser;
import com.sina.microblog.events.MicroBlogErrorEvent;
import com.sina.microblog.events.MicroBlogEvent;
import com.sina.microblog.utils.StringEncoders;
import com.yf.weibofans.Test;
import com.yf.weibofans.container.Container;
import com.yf.weibofans.copyright.Copyright;
import com.yf.weibofans.link.OpenWindow;
import com.yf.weibofans.statics.Statics;
import com.yf.weibofans.statics.FansEvent;

import components.Profile;

import flash.display.MovieClip;
import flash.display.SimpleButton;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.MouseEvent;
import flash.events.SecurityErrorEvent;
import flash.external.ExternalInterface;
import flash.net.LocalConnection;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestHeader;
import flash.net.URLRequestMethod;
import flash.net.URLVariables;
import flash.system.Security;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;

import mx.controls.Alert;
import mx.core.UIComponent;

import spark.components.Application;

import org.bytearray.gif.decoder.GIFDecoder;
import org.bytearray.gif.events.FileTypeEvent;
import org.bytearray.gif.events.FrameEvent;
import org.bytearray.gif.events.GIFPlayerEvent;
import org.bytearray.gif.events.TimeoutEvent;
import org.bytearray.gif.player.GIFPlayer;


private var mb:MicroBlog;

private var myUid:int;//用户uid
private var friendArr:Array = new Array();//关注id
private var followerArr:Array = new Array();//粉丝id
private var mutualityArr:Array = new Array();//互粉id
private var unfollowArr:Array = new Array();//非粉丝的关注的人
private var counter:int = 0;//互粉记数
private var unfollowDataArr:Array = new Array();//非粉丝MicroBlogUser，头像地址和昵称
private var _myGIFPlayer:GIFPlayer = new GIFPlayer();//加载会动的gif用




/**
 *  同一个api不能注册两个响应事件，否则不响应第二个，暂不知为什么。
 * 
 * 
 */

private function init():void
{
	mb = new MicroBlog();
	
	if(this.parameters.tag != null && this.parameters.tag != "")
	{
		if(this.parameters.tag == "out")
		{
			//站外
			mb.consumerKey = Statics.appKey_out;
			mb.consumerSecret = Statics.appSecrect_out;
			Statics.copyRightName = Statics.appName_out+" "+Statics.version;
		}
		else if(this.parameters.tag == "in")
		{
			//站内
			mb.consumerKey = Statics.appKey_in;
			mb.consumerSecret = Statics.appSecrect_in;
			Statics.copyRightName = Statics.appName_in+" "+Statics.version;
		}
		mb.proxyURI = this.parameters.proxy; //写你自己部署的代理接口地址
		mb.addEventListener(MicroBlogEvent.LOGIN_RESULT, onLoginResult);
		mb.addEventListener(MicroBlogErrorEvent.LOGIN_ERROR, onLoginErrorResult);
		mb.login();
	}
	else
	{
		alertText.text = Statics.parametersErrorText;
	}
	
	
}

/*
* 成功登录，获取到access_token，expires_in和refresh_token
*/
private function onLoginResult(e:MicroBlogEvent):void
{
	mb.removeEventListener(MicroBlogEvent.LOGIN_RESULT, onLoginResult);
	mb.removeEventListener(MicroBlogErrorEvent.LOGIN_ERROR, onLoginErrorResult);
	getUID();
}

private function onLoginErrorResult(event:MicroBlogErrorEvent):void
{
	mb.removeEventListener(MicroBlogEvent.LOGIN_RESULT, onLoginResult);
	mb.removeEventListener(MicroBlogErrorEvent.LOGIN_ERROR, onLoginErrorResult);
	//Test.t("onLoginErrorResult : "+event.message);
	alertText.text = Statics.loginErrorText;
}

/**
 * 首先获取uid
 */
private function getUID():void
{
	//获取博主信息
	mb.addEventListener(FansEvent.MYUID_RESULT, getUIDResult);
	mb.addEventListener(FansEvent.MYUID_ERROR, getUIDError);
	mb.callWeiboAPI("2/account/get_uid", null, "GET", FansEvent.MYUID_RESULT, FansEvent.MYUID_ERROR); 
}

/**
 * 请求uid成功 
 * @param event
 * 
 */
private function getUIDResult(event:MicroBlogEvent):void
{
	mb.removeEventListener(FansEvent.MYUID_RESULT, getUIDResult);
	mb.removeEventListener(FansEvent.MYUID_ERROR, getUIDError);

	myUid = event.result.uid;

	// 2/users/show的监听
	mb.addEventListener(FansEvent.LOAD_USER_INFO_RESULT, loadUserInfoHandler);
	mb.addEventListener(FansEvent.LOAD_USER_INFO_ERROR, loadUserInfoErrorHandler);
	
	//请求自己的信息
	mb.callWeiboAPI("2/users/show", {"uid":myUid}, "GET", FansEvent.LOAD_USER_INFO_RESULT, FansEvent.LOAD_USER_INFO_ERROR); 
}

/**
 * 请求uid失败
 * @param event
 * 
 */
private function getUIDError(event:MicroBlogErrorEvent):void
{
	mb.removeEventListener(FansEvent.MYUID_RESULT, getUIDResult);
	mb.removeEventListener(FansEvent.MYUID_ERROR, getUIDError);
	alertText.text = Statics.myUIDErrorText;
	//Test.t("getUIDError: "+event.message);
}


/*------------------------------------ 验证的分割线 ---------------------------------------------*/

/**
 * 	1.获取关注id
 * 	2.获取粉丝id
 * 	3.点击分析，比较关注和粉丝，获取互粉id
 * 	4.根据互粉id逐个请求对应信息MicroBlogUser，并记录头像地址和昵称
 * 	5.互粉id逐个请求完，展示
 * 
 */ 


private function main():void
{
	var copyright:Copyright=new Copyright(this, Statics.copyRightName);
	mainPanel.title = Statics.panelTitle;
	
	analysisBtn.addEventListener(MouseEvent.CLICK, analysisBtnHandler);
	
	//关注
	mb.addEventListener(FansEvent.FRIEND_ID_LIST_RESULT, friendIDListHandler);
	mb.addEventListener(FansEvent.FRIEND_ID_LIST_ERROR, friendIDListErrorHandler);
	
	//粉丝
	mb.addEventListener(FansEvent.FOLLOWERS_ID_LIST_RESULT, followersIDListHandler);
	mb.addEventListener(FansEvent.FOLLOWERS_ID_LIST_ERROR, followersIDListErrorHandler);

	//请求关注人id列表
	//mb.loadFriendsIDList();
	mb.callWeiboAPI("2/friendships/friends/ids", null, "GET", FansEvent.FRIEND_ID_LIST_RESULT, FansEvent.FRIEND_ID_LIST_ERROR); 
}


/**
 *	关注id列表 
 * @param event
 * 
 */
private function friendIDListHandler(event:MicroBlogEvent):void
{
	mb.removeEventListener(FansEvent.FRIEND_ID_LIST_RESULT, friendIDListHandler);
	mb.removeEventListener(FansEvent.FRIEND_ID_LIST_ERROR, friendIDListErrorHandler);
	
	if(event.result.ids is Array)
	{
		friendArr = event.result.ids as Array;

		//请求粉丝id列表
		//mb.loadFollowersIDList();
		mb.callWeiboAPI("2/friendships/followers/ids", null, "GET", FansEvent.FOLLOWERS_ID_LIST_RESULT, FansEvent.FOLLOWERS_ID_LIST_ERROR); 
	}
	else
	{
		alertText.text = Statics.friendIDListErrorText;
	}
	
}

/**
 *	关注id列表错误 
 * @param event
 * 
 */
private function friendIDListErrorHandler(event:MicroBlogErrorEvent):void
{
	mb.removeEventListener(FansEvent.FRIEND_ID_LIST_RESULT, friendIDListHandler);
	mb.removeEventListener(FansEvent.FRIEND_ID_LIST_ERROR, friendIDListErrorHandler);
	
	//trace("friendIDListErrorHandler : "+event.message);
	alertText.text = Statics.friendIDListErrorText;
}


/**
 *	粉丝id列表 
 * @param event
 * 
 */
private function followersIDListHandler(event:MicroBlogEvent):void
{
	mb.removeEventListener(FansEvent.FOLLOWERS_ID_LIST_RESULT, followersIDListHandler);
	mb.removeEventListener(FansEvent.FOLLOWERS_ID_LIST_ERROR, followersIDListErrorHandler);
	
	if(event.result.ids is Array)
	{
		followerArr = event.result.ids as Array;

		analysisBtn.mouseEnabled = true;
		analysisBtn.alpha = 1;
	}
	else
	{
		alertText.text = Statics.followersIDListErrorText;
	}
}

/**
 *	粉丝id列表错误 
 * @param event
 * 
 */
private function followersIDListErrorHandler(event:MicroBlogErrorEvent):void
{
	mb.removeEventListener(FansEvent.FOLLOWERS_ID_LIST_RESULT, followersIDListHandler);
	mb.removeEventListener(FansEvent.FOLLOWERS_ID_LIST_ERROR, followersIDListErrorHandler);
	
	//trace("followersIDListErrorHandler : "+event.message);
	alertText.text = Statics.followersIDListErrorText;
}




/**
 *	用户信息 
 * @param event
 * 
 */
private function loadUserInfoHandler(event:MicroBlogEvent):void
{
	if(event.result.id == myUid)
	{
		//用户自己-----------
		userAvatar.source = event.result.profile_image_url;//头像
		userName.text = event.result.screen_name; //昵称
		
		main();
	}
	else
	{
		//其他人-----------
		unfollowDataArr.push({avatar:event.result.profile_image_url, name:event.result.screen_name});
		
		if((unfollowArr.length-1) == counter)
		{
			counter = 0;
			
			//展示
			Container.cleanContainer(listContainer);
			var len:int = unfollowDataArr.length;
			for(var i:int = 0; i<len; i++)
			{
				var profile:Profile = new Profile();
				profile.profile_avatar.source=unfollowDataArr[i].avatar; //头像
				profile.profile_name.text=unfollowDataArr[i].name; //昵称
				profile.x = (i%11) * (profile.width + 3);
				profile.y = Math.floor(i/11) * profile.height;
				
				listContainer.addElement(profile);
			}
			
			unfollowDataArr = [];
			friendArr = [];
			followerArr = [];
			mutualityArr = [];
			//unfollowArr = [];
			
			alertText.text = Statics.notYourFollowers(unfollowArr.length);
			analysisBtn.mouseEnabled = true;
			analysisBtn.alpha = 1;
		}
		else
		{
			counter++;
			requestHandler();
		}
	}
}

/**
 *	用户信息失败 
 * @param event
 * 
 */
private function loadUserInfoErrorHandler(event:MicroBlogErrorEvent):void
{
	var unfollowArrNull:Boolean = unfollowArr.length != 0;//非粉丝的关注的人unfollowArr为空，则表示请求自己的信息出错。
	if((unfollowArr.length-1) == counter && unfollowArrNull)
	{
		//unfollowArr都请求完了
		counter = 0;
	}
	else if((unfollowArr.length-1) != counter && unfollowArrNull)
	{
		//unfollowArr未请求完，继续。。。
		counter++;
		requestHandler();
	}
	else if(!unfollowArrNull)
	{
		//请求自己信息出错
		alertText.text = Statics.myInfoErrorText;
	}
}



/**
 *	分析按钮 
 * @param event
 * 
 */
private function analysisBtnHandler(event:MouseEvent):void
{
	analysisBtn.mouseEnabled = false;
	analysisBtn.alpha = .5;
	alertText.text = Statics.analysing;
	
	Container.cleanContainer(listContainer);
	
	//加载waiting gif
	var request:URLRequest = new URLRequest(Statics.waitingGIFPath);
	_myGIFPlayer.addEventListener(GIFPlayerEvent.COMPLETE, onCompleteGIF);
	_myGIFPlayer.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
	_myGIFPlayer.load(request);

	analysisHandler();
}

/**
 *	加载waiting gif成功 
 * @param event
 * 
 */
private function onCompleteGIF(event:GIFPlayerEvent):void
{
	var temp:UIComponent = new UIComponent();  
	listContainer.addElement(temp);
	temp.x = (listContainer.width - _myGIFPlayer.width) / 2;
	temp.y = 180;
	temp.addChild(_myGIFPlayer);
}

/**
 * 加载waiting gif失败
 * @param pEvt
 * 
 */
private function onIOError(pEvt:IOErrorEvent):void
{
	
}


/**
 *	分析 
 * 
 */
private function analysisHandler():void
{
	var len1:int = friendArr.length;
	var len2:int = followerArr.length;

	for(var i:int = 0; i<len1; i++)
	{
		for(var j:int=0; j<len2; j++)
		{
			if(friendArr[i] == followerArr[j])
			{
				mutualityArr.push(friendArr[i]);//互粉的
			}
		}
	}

	//把互粉的标记出，以便替换掉，friendArr内容已变!
	var len3:int = mutualityArr.length;
	for(var k:int=0; k<len1; k++)
	{
		for(var l:int=0; l<len3; l++)
		{
			if(friendArr[k] == mutualityArr[l])
			{
				friendArr.splice(k, 1, "xxx");	
			}
		}
	}
	
	//不是互粉的关注放入unfollowArr
	for(var m:int=0; m<len1; m++)
	{
		if(friendArr[m] != "xxx")
		{
			unfollowArr.push(friendArr[m]);
		}	
	}
	
	requestHandler();
}

/**
 *	按id请求用户信息 
 * 
 */
private function requestHandler():void
{
	//根据id请求用户信息
	//mb.loadUserInfo(unfollowArr[counter], unfollowArr[counter]);//loadUserInfoHandler

	var _obj:Object = {"uid":unfollowArr[counter]};
	mb.callWeiboAPI("2/users/show", _obj, "GET", FansEvent.LOAD_USER_INFO_RESULT, FansEvent.LOAD_USER_INFO_ERROR);//请求到了，响应事件未触发，网慢？
}




